<?php

defined('BASEPATH') or die('No direct script access allowed');

/**
 * 移动端会员控制器
 * @author  Karson
 * @name    user.php
 * @since   2013-8-6 21:38:40
 */
class User_Controller extends Controller {

    function index() {
        check_level();

        $expense_list = array();
        $this->db->query("SELECT * FROM {pre}bill WHERE type='expense' AND user_id='{$this->auth->user_id}' ORDER BY id DESC LIMIT 5", "bi");
        while ($row = $this->db->get_array("bi")) {
            $row['category'] = get_category($row['category_id']);
            if (isset($row['category']['father_id'])) {
                $row['father_category'] = get_category($row['category']['father_id']);
            } else {
                $row['father_category'] = array('id' => 0, 'name' => '未知');
            }
            $row['account'] = get_account($row['account_id']);
            $expense_list[] = $row;
        }
        $this->view->assign("expense_list", $expense_list);

        $real = $budget = array('expense' => array());
        $where = ' AND occurtime >= ' . get_unixtime('month') . ' AND occurtime <=' . get_unixtime('month', 0, 'end');
        $this->db->query("SELECT SUM(amount) AS amounts, category_id FROM {pre}bill
            WHERE type='expense' {$where}
            GROUP BY category_id", 'lii');
        while ($row = $this->db->get_array('lii')) {
            if ($row['category_id'] == '') {
                $real['expense']['all'] = (int) $row['amounts'];
            } else {
                $category = get_category($row['category_id']);
                if ($category) {
                    $father_id = $category['father_id'];
                    if (isset($real['expense'][$father_id])) {
                        $real['expense'][$father_id] += (int) $row['amounts'];
                    } else {
                        $real['expense'][$father_id] = (int) $row['amounts'];
                    }
                }
            }
            if ($row['month'] == '' && $row['category_id'] == '') {
                $real['expense']['total'] = (int) $row['amounts'];
            }
        }

        $year = (int) date("Y");
        $month = (int) date("m");
        $row = $this->db->one("SELECT `month`, `content` FROM {pre}budget WHERE year='{$year}' AND month='{$month}' AND user_id='{$this->auth->user_id}'");
        if ($row) {
            $content = json_decode($row['content'], true);
            $budget['expense'] = isset($content['expense']) ? $content['expense'] : array();
            $budget['expense']['all'] = array_sum($budget['expense']);
        }

        $this->view->assign("budget", $budget);
        $this->view->assign("real", $real);
        $this->view->assign("startdate", get_unixtime('month', 0, 'begin'));
        $this->view->assign("enddate", get_unixtime('month', 0, 'end'));

        $income = $expense = 0;
        $this->db->query("SELECT SUM(amount) AS amounts,type FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type IN ('income','expense') {$where} GROUP BY type");
        while ($row = $this->db->get_array()) {
            if ($row['type'] == 'income') {
                $income = $row['amounts'];
            } else {
                $expense = $row['amounts'];
            }
        }
        $data = array('typelist' => $this->type,);
        $this->db->query("SELECT SUM(balance) AS nums,type FROM {pre}account WHERE user_id='{$this->auth->user_id}' GROUP BY type");
        $asset = array();
        foreach ($this->account->account_type as $k => $v) {
            $asset[$k] = 0;
        }
        while ($row = $this->db->get_array()) {
            $asset[$row['type']] = $row['nums'];
        }

        //资产合计
        $asset['total'] = array_sum($asset) - $asset['credit'];
        $data['show']['asset'] = $asset;
        //债权
        $one = $this->db->one("SELECT SUM(amount) AS amount, SUM(outstanding) AS outstanding FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type='borrow' AND category_id='1'");
        $one['total'] = $one['settled'] = $one['amount'] - $one['outstanding'];
        $data['show']['creditor'] = $one;
        //债务
        $one = $this->db->one("SELECT SUM(amount) AS amount, SUM(outstanding) AS outstanding FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type='borrow' AND category_id='2'");
        $one['settled'] = $one['amount'] - $one['outstanding'];
        $asset['credit'] = -$asset['credit'];
        $one['total'] = $one['outstanding'] + $asset['credit'];
        $data['show']['debtor'] = $one;
        //合计

        $data['show']['income'] = $income;
        $data['show']['expense'] = $expense;
        $data['out'] = get_category_list('expense');
        $data['notice_list'] = get_notice_list(5);

        render("mobile/user/index", $data);
    }

    /**
     * 会员登录
     */
    function login() {
        $url = isset($_GET['url']) ? $_GET['url'] : '/mobile/user/';
        if ($this->auth->is_login())
            show_message('你已经登录，请不要重复登录', $url, 2000, 'help');
        if ($this->form->is_submit('post')) {
            $code = 0;
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $keeptime = $this->input->post('savecookie') == 'on' ? 86400 * 30 : 0;
            $today = get_unixtime('day');
            //统计今天登录失败次数
            $failure = $this->db->one("SELECT COUNT(*) AS num FROM {pre}login_failure WHERE username='{$username}' AND createtime>{$today}");
            if ($failure['num'] >= 50 && $username) {
                $field = is_email($username) ? 'email' : 'username';
                $one = $this->db->one("SELECT * FROM {pre}user WHERE {$field}='{$username}'");
                //根据不同判断来发邮件
                if (is_array($one) && $one['email']) {
                    $data['notice_box'] = "对不起！您已经尝试登录5次，我们已经向您的邮箱发送了一封含有免登录链接的邮件，您可以点击链接进入会员中心修改密码！";
                    if ($failure['num'] == 5) {
                        login_failure($username, $password, "登录超过指定次数");
                        $url = site_url("/user/shortcut/webclient/{$one['id']}/" . md5s($one['id'] . $one['password'], 16) . "/user/profile/auth/", 1);
                        $content = "Hi, {$one['username']}：<br />我们发现您在登录返券网时遇到了困难，点击以下链接可以自动登录并设置新的登录密码。<a href='{$url}'>{$url}</a><br />如果上面的链接无法点击，您也可以复制链接，粘贴到浏览器地址栏内打开。";
                        send_email("Hi, {$one['username']} 返券网免登录确认", $content, $one['email']);
                    }
                } else {
                    $data['notice_box'] = "对不起！系统只允许尝试登录5次！请尝试<a href='/user/findpwd/'>找回密码</a>或与我们取得联系！";
                }
            } else {
                $captcha = isset($_POST['captcha']) ? strtoupper($this->input->post('captcha')) : null;
                if (!is_email($username) && ($username == '' || strlen($username) < 3 || strlen($username) > 16)) {
                    $text = '用户名输入有误';
                }
                if ($password == '' || strlen($password) < 3 || strlen($password) > 16) {
                    $text = '密码输入有误';
                }
                if (!isset($text)) {
                    if (is_email($username)) {
                        $row = $this->db->one("SELECT id,username,email FROM {pre}user WHERE email='{$username}'");
                        if (!is_array($row)) {
                            $text = "您所登录的用户未找到！";
                        } else {
                            $username = $row['username'];
                        }
                    }
                    if (!isset($text)) {
                        if ($this->auth->login($username, $password, $keeptime)) {
                            $code = 1;
                            $text = "登录成功";
                        } else {
                            $text = $this->auth->error;
                        }
                    }
                }
                if ($username && $password) {
                    $username = $this->input->post('username');
                    login_failure($username, $password, $text);
                }
                $data['notice_box'] = $text;
            }
            json_output($code, $text);
        }
        $data['url'] = $url;
        $data['title'] = "会员登录";
        render("mobile/user/login", $data);
    }

    /**
     * 注册新会员
     */
    function register() {
        $url = isset($_GET['url']) ? $_GET['url'] : '/user/';
        if ($this->auth->is_login())
            show_message('你已经登录，请不要重复注册', $url, 2000, 'help');
        if ($this->form->is_submit('post')) {
            $code = 0;
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $repassword = $this->input->post('repassword');
            $email = $this->input->post('email');
            if (!is_email($email))
                $text = 'Email格式不正确';
            if ($username == '' || strlen($username) < 3 || strlen($username) > 15)
                $text = '用户名长度必须大于3位,小于15位';
            if ($password == '' || strlen($password) < 3 || strlen($password) > 15 || $password != $repassword)
                $text = '密码输入有误';
            $row = $this->db->one("SELECT id FROM {pre}user WHERE username='{$username}' OR email='{$email}'");
            if (is_array($row))
                $text = '用户名或Email已经存在';
            $time = time();
            $ip = get_ip();
            $referer = $this->cookie->get('referer_url');
            if (!isset($text)) {
                $new_id = $this->auth->register($username, $password, $email);
                if (!isset($text) && is_numeric($new_id) && $new_id > 0) {
                    $needconfirm = false;
                    $notetitle = str_replace('{username}', $username, $this->config['note']['register_title']);
                    $notecontent = str_replace('{username}', $username, $this->config['note']['register_content']);
                    $emailtitle = str_replace('{username}', $username, $this->config['email']['register_title']);
                    $emailcontent = str_replace('{username}', $username, $this->config['email']['register_content']);
                    //如果有找到confirmurl则表示需要邮箱验证
                    if ($this->config['email_confirm'] && $emailcontent && stripos($emailcontent, '{confirmurl}') !== false) {
                        $needconfirm = true;
                        $confirmcode = sha1($new_id . $username);
                        $confirmurl = site_url("user/confirm/active/{$new_id}/{$confirmcode}/", 1);
                        $emailcontent = str_replace('{confirmurl}', $confirmurl, $emailcontent);
                    }
                    //发送欢迎短信、邮件、显示成功信息！
                    if ($notecontent) {
                        send_note($notetitle, $notecontent, $new_id);
                    }
                    if ($emailcontent) {
                        //因速度影响,暂停发送邮件
                        //send_email($emailtitle, $emailcontent, $email);
                    }
                    $this->auth->login($username, $password);
                    invite($new_id);
                    $code = 1;
                    $text = "注册成功";
                } else {
                    $text = '注册失败！请检查输入的内容是否正确！';
                }
            }
            json_output($code, $text);
        }
        $data['url'] = $url;
        $data['title'] = "会员注册";
        render("mobile/user/register", $data);
    }

    /**
     * 注销登录
     */
    function logout() {
        $this->auth->logout();
        go("/mobile/user/login/");
    }

}